//
//  ViewController.m
//  WeightMaster
//
//  Created by sungeo on 15/8/14.
//  Copyright (c) 2015年 buddysoft. All rights reserved.
//

#import "HomeViewController.h"
#import <RandomSequence.h>
#import <DateTools.h>
#import <EXTScope.h>
#import <NSObject+GLPubSub.h>
#import "SliderLabelContainer.h"
#import "UIScrollView+TwitterCover.h"
#import "BDFoundation.h"
#import "Masonry.h"
#import "DataManager.h"
#import "WMModels.h"
#import "WeightsChartController.h"
#import "WeightsHistoryViewController.h"
#import "BmiDetailViewController.h"
#import "SettingsEntryView.h"
#import "SettingsViewController.h"
#import "CreateWeightViewController.h"
#import "TestCode.h"

#define CIRCLE_RADIUS   28
#define ARC_HIGHT   20
#define DIGIT_WIDTH 27
#define DIGIT_HEIGHT    50
#define DOT_VIEW_TAG    1000

#define RED_COLOR   RGB(255, 77, 113)

#define COLOR_BAR_LEFT_OFFSET 20

@interface HomeViewController () {
    UILabel * _dotContainer;
    UIView * _weightView;
    UILabel * _weightUnitLabel;
    UIScrollView * _scrollView;
    CAGradientLayer * _colorBarLayer;
    UILabel * _bmiLable;
    UIView * _bmiView;
    UIButton * _recordButton;
    UILabel * _coverLabel;
    
    SettingsEntryView * _settingEntry;
    WeightsChartController * _weightsChartController;
    
    NSArray * _titles;
    NSArray * _bmiCriticalPoints;

    NSMutableArray * _weightsValue; // 保存体重每位的数字
}

@end

@implementation HomeViewController

#pragma 私有函数
- (void)createArcView {
    UIBezierPath * path = [UIBezierPath bezierPath];
    
    [path moveToPoint:CGPointMake(0, CHTwitterCoverViewHeight - ARC_HIGHT)];
    [path addCurveToPoint:CGPointMake(kScreen_CenterX - CIRCLE_RADIUS, CHTwitterCoverViewHeight) controlPoint1:CGPointMake((kScreen_CenterX - CIRCLE_RADIUS)/2.0, CHTwitterCoverViewHeight) controlPoint2:CGPointMake(kScreen_CenterX - CIRCLE_RADIUS, CHTwitterCoverViewHeight)];
    
    [path addArcWithCenter:CGPointMake(kScreen_CenterX, CHTwitterCoverViewHeight) radius:CIRCLE_RADIUS startAngle:0 endAngle:2 * M_PI clockwise:YES];
    
    [path addCurveToPoint:CGPointMake(kScreen_Width, CHTwitterCoverViewHeight - ARC_HIGHT) controlPoint1:CGPointMake(kScreen_CenterX + CIRCLE_RADIUS + (kScreen_CenterX - CIRCLE_RADIUS)/2.0, CHTwitterCoverViewHeight) controlPoint2:CGPointMake(kScreen_Width, CHTwitterCoverViewHeight - ARC_HIGHT)];
    
    [path addLineToPoint:CGPointMake(kScreen_Width, CHTwitterCoverViewHeight)];
    [path addLineToPoint:CGPointMake(0, CHTwitterCoverViewHeight)];

    CAShapeLayer * shapeLayer = [[CAShapeLayer alloc] init];
    shapeLayer.path = [path CGPath];
    shapeLayer.fillColor = [[UIColor whiteColor] CGColor];
    [_scrollView.layer addSublayer:shapeLayer];
    
    path = [UIBezierPath bezierPath];
    CGFloat arrowH = 10.0;
    CGFloat arrowW = 20;
    CGFloat arrowY = CHTwitterCoverViewHeight - arrowH - 5;
    [path moveToPoint:CGPointMake(kScreen_CenterX - arrowW/2.0, arrowY)];
    [path addLineToPoint:CGPointMake(kScreen_CenterX,arrowY + arrowH)];
    [path addLineToPoint:CGPointMake(kScreen_CenterX + arrowW/2.0,arrowY)];
    path.lineWidth = 2.0;
    
    CAShapeLayer * arrowLayer = [[CAShapeLayer alloc] init];
    arrowLayer.path = [path CGPath];
    arrowLayer.strokeColor = [RGB(255, 77, 113) CGColor];
    arrowLayer.fillColor = [[UIColor clearColor] CGColor];
    [_scrollView.layer addSublayer:arrowLayer];

}

- (void)makeColorBar {
    UILabel * bmiDescriptionLabel = [[UILabel alloc] init];
    bmiDescriptionLabel.font = [UIFont systemFontOfSize:11.0];
    bmiDescriptionLabel.text = @"BMI指数";
    bmiDescriptionLabel.textAlignment = NSTextAlignmentCenter;
    bmiDescriptionLabel.textColor = RGB(135, 135, 135);
    [_scrollView addSubview:bmiDescriptionLabel];
    [bmiDescriptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_weightUnitLabel.mas_bottom).offset(55);
    }];
    
    [bmiDescriptionLabel layoutIfNeeded];
    
    if (_colorBarLayer == nil) {
        _colorBarLayer = [CAGradientLayer layer];
        _colorBarLayer.frame = CGRectMake(COLOR_BAR_LEFT_OFFSET, bmiDescriptionLabel.frame.origin.y + 50, kScreen_Width-COLOR_BAR_LEFT_OFFSET*2 , 10);
        _colorBarLayer.cornerRadius = 5.0;
        
        UIView * backgroundView = [[UIView alloc] initWithFrame:CGRectMake(COLOR_BAR_LEFT_OFFSET, bmiDescriptionLabel.frame.origin.y + 20, kScreen_Width-COLOR_BAR_LEFT_OFFSET*2 , 50)];
        backgroundView.backgroundColor = [UIColor clearColor];
        backgroundView.userInteractionEnabled = NO;
        [backgroundView addAction:@selector(showBmiDetail) target:self];
        [_scrollView addSubview:backgroundView];
    }
    
    _colorBarLayer.startPoint = CGPointMake(0, 0);
    _colorBarLayer.endPoint = CGPointMake(1, 0);
    
    // 颜色分配
    _colorBarLayer.colors = @[(__bridge id)RGB(51, 207, 244).CGColor,
                          (__bridge id)RGB(53, 255, 50).CGColor,
                          (__bridge id)RGB(255, 252, 0).CGColor,
                          (__bridge id)RGB(255, 157, 0).CGColor,
                          (__bridge id)RGB(255, 62, 45).CGColor];
    
    UIBezierPath * path;
    CAShapeLayer * shapeLayer;
    UILabel * label;
    NSInteger count = [_titles count];
    CGFloat separatorWidth = (kScreen_Width - COLOR_BAR_LEFT_OFFSET*2)/count;
    for (NSInteger index = 1; index < count + 1; index++) {
        path = [UIBezierPath bezierPathWithRect:CGRectMake(separatorWidth * index, 0, 1, 10)];
        shapeLayer = [[CAShapeLayer alloc] init];
        shapeLayer.path = [path CGPath];
        shapeLayer.fillColor = [[UIColor whiteColor] CGColor];
        [_colorBarLayer addSublayer:shapeLayer];
        
        label = [[UILabel alloc] init];
        label.text = [_titles objectAtIndex:index-1];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = RGB(50, 50, 50);
        [label addAction:@selector(showBmiDetail) target:self];
        [_scrollView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *maker) {
            maker.top.equalTo(bmiDescriptionLabel.mas_bottom).offset(CGRectGetHeight(_colorBarLayer.frame) + 45);
            maker.leading.mas_equalTo(COLOR_BAR_LEFT_OFFSET + (index-1)*separatorWidth);
            maker.width.mas_equalTo(separatorWidth);
        }];
    }

    [_scrollView.layer addSublayer:_colorBarLayer];
}

- (void)createBmiView {
    CGFloat const circleWidth = 16.0;
    _bmiView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, circleWidth, circleWidth)];
    _bmiView.backgroundColor = RED_COLOR;
    [_bmiView makeCircle];
    [_bmiView addBorderWithWidth:1 withColor:[UIColor whiteColor]];
    [_bmiView addAction:@selector(showBmiDetail) target:self];
    [_scrollView addSubview:_bmiView];
    [_bmiView mas_makeConstraints:^(MASConstraintMaker *maker) {
        maker.width.mas_equalTo(circleWidth);
        maker.height.mas_equalTo(circleWidth);
        maker.leading.mas_equalTo(COLOR_BAR_LEFT_OFFSET);
        maker.top.mas_equalTo(_colorBarLayer.frame.origin.y - 3);
    }];
    
    WMWeight * weight = [[WMDataCache sharedInstance] latestWeight];
    NSNumber * height = [WMAppSetting sharedInstance].height;
    CGFloat currentBMI = [[WMHelper BMIForWeight:weight.value height:height] floatValue];
    
    _bmiLable = [[UILabel alloc] init];
    _bmiLable.text = [NSString stringWithFormat:@"%.1lf", currentBMI];
    _bmiLable.textAlignment = NSTextAlignmentCenter;
    _bmiLable.textColor = RED_COLOR;
    [_bmiLable addAction:@selector(showBmiDetail) target:self];
    [_scrollView addSubview:_bmiLable];
    [_bmiLable mas_makeConstraints:^(MASConstraintMaker *maker) {
        maker.top.mas_equalTo(_colorBarLayer.frame.origin.y - 25);
        maker.centerX.equalTo(_bmiView);
    }];
}

- (void)createCurrentWeightView {
    WMWeight * weight = [[WMDataCache sharedInstance] latestWeight];
    NSString * currentWeight = [weight.value stringValue];
    NSInteger count = currentWeight.length;
    
    _weightView = [[UIView alloc] init];
    [_weightView setUserInteractionEnabled:NO];
    [_weightView removeFromSuperview];
    
    [_scrollView addSubview:_weightView];
    [_weightView mas_makeConstraints:^(MASConstraintMaker *maker) {
        maker.centerX.equalTo(self.view);
        maker.width.mas_equalTo(DIGIT_WIDTH*count);
        maker.height.mas_equalTo(DIGIT_HEIGHT);
        maker.top.mas_equalTo(CHTwitterCoverViewHeight - 130);
    }];
}

- (void)createDigitView {
    static NSString * sLastDigitString = nil;
    
    [_weightsValue removeAllObjects];
    
    WMWeight * latestWeight = [[WMDataCache sharedInstance] latestWeight];
    NSString * currentWeight = [WMHelper stringValueForWeight:latestWeight.value withUnit:[WMAppSetting sharedInstance].weightUnit];
    
    if ([currentWeight isEqualToString:sLastDigitString]) {
        NSLog(@"数字相等，无需刷新界面体重数字: %@", currentWeight);
        return;
    }
    
    sLastDigitString = currentWeight;
    
    NSInteger count = currentWeight.length;
    
    if ([WMAppSetting sharedInstance].coverImage) {
        _scrollView.twitterCoverView.image = [WMAppSetting sharedInstance].coverImage;
    }
    
    [_weightView mas_updateConstraints:^(MASConstraintMaker *maker) {
        maker.width.mas_equalTo(DIGIT_WIDTH*count);
    }];
    
    for (NSInteger index = 1; index < 5; index++) {
        SliderLabelContainer * container = (SliderLabelContainer *)[self.view viewWithTag:index];
        if (container) {
            [container removeFromSuperview];
        }
    }
    
    UILabel * dotView = (UILabel *)[self.view viewWithTag:DOT_VIEW_TAG];
    if (dotView) {
        [dotView removeFromSuperview];
    }
    
    NSString * tmpStr;
    NSInteger buttonTag = 1;
    for (NSInteger index = 1; index <= count;index++) {
        tmpStr = [currentWeight substringWithRange:NSMakeRange(index-1,1) ];
        if ([@"." isEqualToString:tmpStr]) {
            UILabel * container = (UILabel *)[self.view viewWithTag:DOT_VIEW_TAG];
            if (nil == container) {
                container = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, DIGIT_WIDTH,DIGIT_HEIGHT)];
                container.text = @".";
                container.tag = DOT_VIEW_TAG;
                container.textColor = [UIColor whiteColor];
                container.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:50.0];
            }
            [_weightView addSubview:container];
            [container mas_makeConstraints:^(MASConstraintMaker *maker) {
                maker.leading.mas_equalTo(DIGIT_WIDTH * (index - 1));
                maker.width.mas_equalTo(DIGIT_WIDTH);
                maker.height.mas_equalTo(DIGIT_HEIGHT);
                maker.top.equalTo(_weightView);
            }];
        }else {
            SliderLabelContainer * container = (SliderLabelContainer *)[self.view viewWithTag:index];
            if (nil == container) {
                container = [[SliderLabelContainer alloc] initWithFrame:CGRectMake(0, 0, DIGIT_WIDTH,DIGIT_HEIGHT)];
            }
            [_weightsValue addObject:tmpStr];
            container.tag = buttonTag;
            [_weightView addSubview:container];
            [container mas_updateConstraints:^(MASConstraintMaker *maker) {
                maker.leading.mas_equalTo(DIGIT_WIDTH * (index - 1));
                maker.width.mas_equalTo(DIGIT_WIDTH);
                maker.height.mas_equalTo(DIGIT_HEIGHT);
                maker.top.equalTo(_weightView);
            }];
            buttonTag ++;
        }
    }
    
    // 刷新数字到目标位置
    count = [_weightsValue count];
    for (NSInteger index = 1; index <= count; index++) {
        SliderLabelContainer * container = (SliderLabelContainer *)[self.view viewWithTag:index];
        [container scrollToNum:[[_weightsValue objectAtIndex:index-1] integerValue]];
    }
}


- (void)createWeightUnitView {
    _weightUnitLabel = [[UILabel alloc] init];
    _weightUnitLabel.text = [WMHelper stringValueForUnit:[WMAppSetting sharedInstance].weightUnit];
    _weightUnitLabel.textColor = [UIColor whiteColor];
    _weightUnitLabel.textAlignment = NSTextAlignmentCenter;
    _weightUnitLabel.font = [UIFont systemFontOfSize:15];
    [_scrollView addSubview:_weightUnitLabel];
    [_weightUnitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(80);
        make.height.mas_equalTo(25);
        make.top.equalTo(_weightView.mas_bottom).offset(10.0);
    }];
    
    UIView * weightUnitbackgroundView = [[UILabel alloc] init];
    weightUnitbackgroundView.backgroundColor = RGB(255, 255, 255);
    weightUnitbackgroundView.alpha = 0.3;
    [weightUnitbackgroundView makeCornorRadius:13.0];
    [_scrollView addSubview:weightUnitbackgroundView];
    [weightUnitbackgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_weightUnitLabel);
    }];
}

- (void)createSettingEntryView{
    SettingsEntryView * entryView = [[SettingsEntryView alloc] init];
    [entryView addClickedTarget:self selector:@selector(enterSettings:)];
    [self.view addSubview:entryView];
    @weakify(self);
    [entryView mas_makeConstraints:^(MASConstraintMaker * maker){
        @strongify(self);
        maker.leading.equalTo(self.view.mas_left).offset(8);
        maker.top.equalTo(self.view.mas_top).offset(24);
        maker.width.equalTo(@(61));
        maker.height.equalTo(@(61));
    }];
    _settingEntry = entryView;
}

- (void)enterSettings:(id)sender{
    SettingsViewController * vc = [[SettingsViewController alloc] initWithStyle:UITableViewStyleGrouped];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)createScrollView {
    _scrollView = [[UIScrollView alloc] init];
    
    CGFloat offset = 10;
    if (iPhone4) {
        offset += 45;
    }
    [_scrollView setContentSize:CGSizeMake(kScreen_Width, kScreen_Height + offset)];
    [self.view addSubview:_scrollView];
    [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    UIImage * coverImage = [[WMAppSetting sharedInstance] coverImage];
    if (coverImage) {
        [_scrollView addTwitterCoverWithImage:coverImage];
    }else{
        [_scrollView addTwitterCoverWithImage:[UIImage imageNamed:@"default_bg.jpg"]];
    }
    
    [self subscribe:WMCoverChanged handler:^(GLEvent * event){
        if (_coverLabel) {
            [_coverLabel removeFromSuperview];
            _coverLabel = nil;
        }
        _scrollView.twitterCoverView.image = [WMAppSetting sharedInstance].coverImage;
    }];
}

- (void)createWeightsChartView{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_weightsChartController == nil) {
            _weightsChartController = [[WeightsChartController alloc] init];
            _weightsChartController.delegate = self;
            [_scrollView addSubview:_weightsChartController.containerView];
        }
    });

    @weakify(self);
    [_weightsChartController.containerView mas_makeConstraints:^(MASConstraintMaker * maker){
        @strongify(self);
        maker.leading.equalTo(self.view.mas_leading);
        maker.trailing.equalTo(self.view.mas_trailing);
        maker.top.equalTo(_bmiView.mas_bottom).offset(30);
        maker.height.equalTo(@(150));
    }];
    
    _weightsChartController.items = [[WMDataCache sharedInstance] latest5Weights];
}

- (void)createRecordButton {
    [_scrollView updateConstraints];
    
    UIButton * button = [[UIButton alloc] init];
    button.backgroundColor = RED_COLOR;
    [button setTitle:@"记体重" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(addRecordClicked:) forControlEvents:UIControlEventTouchUpInside];
    [button makeCornorRadius:18.0];
    [_scrollView addSubview:button];
    CGFloat offset = 50;
    if (iPhone4 || iPhone5) {
        offset = 10;
    }
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(_scrollView).with.multipliedBy(0.85);
        make.centerX.equalTo(_scrollView);
        make.top.equalTo(_weightsChartController.containerView.mas_bottom).offset(offset);
        make.height.mas_equalTo(35);
    }];
    _recordButton = button;
}

- (void)refreshBMIView {
    WMWeight * weight = [[WMDataCache sharedInstance] latestWeight];
    NSNumber * height = [WMAppSetting sharedInstance].height;
    CGFloat currentBMI = [[WMHelper BMIForWeight:weight.value height:height] floatValue];
    if (currentBMI < 0) {
        currentBMI = 0.0;
    }
    if (currentBMI > 45.0) {
        currentBMI = 45.0;
    }
    
    _bmiLable.text = [NSString stringWithFormat:@"%.1lf", currentBMI];
    
    NSInteger count = [_titles count];
    CGFloat separatorWidth = (kScreen_Width - COLOR_BAR_LEFT_OFFSET*2)/count;
    CGFloat offset = COLOR_BAR_LEFT_OFFSET;
    NSInteger index = 0;
    for (NSNumber * point in _bmiCriticalPoints) {
        if (currentBMI <= [point floatValue]) {
            if (0 == index) {
                offset += currentBMI*separatorWidth/[point floatValue];
            }else {
                offset += (currentBMI-[[_bmiCriticalPoints objectAtIndex:(index -1)] floatValue])*separatorWidth/([[_bmiCriticalPoints objectAtIndex:index] floatValue]- [[_bmiCriticalPoints objectAtIndex:(index -1)] floatValue]);
            }
            break;
        }else {
            offset += separatorWidth;
        }
        
        index++;
    }
    
    [_bmiView mas_updateConstraints:^(MASConstraintMaker *maker) {
        maker.leading.mas_equalTo(offset - _bmiView.frame.size.width/2);
    }];
    [_bmiLable mas_updateConstraints:^(MASConstraintMaker *maker) {
        maker.centerX.equalTo(_bmiView);
    }];
    
    [_bmiView setNeedsUpdateConstraints];
    [_bmiView updateConstraintsIfNeeded];
    [UIView animateWithDuration:1.0 animations:^{
        [_bmiView layoutIfNeeded];
        [_bmiLable layoutIfNeeded];
    }];
}

- (void)createBackgroundView {
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, CHTwitterCoverViewHeight, kScreen_Width, 375)];
    view.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:view];
}

- (void)createSetCoverImageView {
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, CHTwitterCoverViewHeight)];
    [_scrollView addSubview:imageView];
    [imageView addAction:@selector(editCoverImage) target:self];
    
    if (nil == [WMAppSetting sharedInstance].coverImage) {
        _coverLabel = [[UILabel alloc] init];
        _coverLabel.text = @"更换封面图片";
        _coverLabel.font = [UIFont systemFontOfSize:13.0];
        _coverLabel.textColor = RGB(255, 255, 255);
        _coverLabel.textAlignment = NSTextAlignmentCenter;
        [_scrollView addSubview:_coverLabel];
        [_coverLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_scrollView);
            make.bottom.equalTo(_weightView.mas_top).offset(-30);
        }];
    }
}

- (void)initView {
    [self createScrollView];
    [self createBackgroundView];
    [self createSettingEntryView];
    [self createArcView];
    [self createCurrentWeightView];
    [self createWeightUnitView];
    [self makeColorBar];
    [self createBmiView];
    [self createWeightsChartView];
    [self createRecordButton];
    [self createSetCoverImageView];
}

- (void)showBmiDetail {
    [self performSegueWithIdentifier:@"ToBmiDetail" sender:self];
}

- (void)editCoverImage {
    LCActionSheet *sheet = [LCActionSheet sheetWithTitle:@"更换封面" buttonTitles:@[@"拍照", @"从相册选择"] redButtonIndex:-1 delegate:self];
    [sheet show];
}

#pragma mark - 事件函数
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _titles = kBMI_LEVEL;
    _bmiCriticalPoints = kBMI_POINT;
    _weightsValue = [[NSMutableArray alloc] initWithCapacity:0];
    
    [self initView];
    
    @weakify(self);
    [self subscribe:WMSettingsChanged handler:^(GLEvent * event){
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新目标体重
            [_settingEntry resetContent];
            
            // 更新体重单位
            _weightUnitLabel.text = [WMHelper stringValueForUnit:[WMAppSetting sharedInstance].weightUnit];
            
            // 更新体重图表
            [_weightsChartController.collectionView reloadData];
        });
    }];
    
    [self subscribe:WeightsChangedNote handler:^(GLEvent * event){
        // 体重数据有改变时，刷新体重图表
        _weightsChartController.items = [[WMDataCache sharedInstance] latest5Weights];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新体重图表
            [_weightsChartController.collectionView reloadData];
        });
    }];
    
    [self subscribe:LastWeightChangedNote handler:^(GLEvent * event){
        @strongify(self);
        dispatch_async(dispatch_get_main_queue(), ^{
            // 更新体重数值
            [self createDigitView];
        });
    }];
    
    [self subscribe:AddWeightNote handler:^(GLEvent * event){
        @strongify(self);
        [self enterAddWeightView];
    }];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (NO == [[DataManager defaultInstance] isAppSetFinished]) {
        [self performSegueWithIdentifier:@"ToGuide" sender:self];
    }else {
        static dispatch_once_t once;
        dispatch_once(&once, ^() {
            [self refreshBMIView];
            
            [self createDigitView];
        });
    }
    
    [_weightsChartController moveToRightestItem];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
}

//#define TestCodeEnabled // FIXME

- (void)addRecordClicked:(id)sender{
#ifndef TestCodeEnabled
    [self enterAddWeightView];
#else
    [[TestCode sharedInstance] showTestMenu];
#endif
}

- (void)enterAddWeightView{
    UIViewController * vc = STORYBOARDVC(@"Main",@"CreateWeightViewController");
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.75];
    [self.navigationController pushViewController:vc animated:NO];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.navigationController.view cache:YES];
    [UIView commitAnimations];
}


#pragma mark - Weights Chart delegate
- (void)weightsChartController:(WeightsChartController *)controller didTouchedImageAtWeightItem:(WMWeight *)weight{
    NSLog(@"点击体重对象：%@", weight.value);
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController * vc = [[WeightsHistoryViewController alloc] init];
        [self.navigationController pushViewController:vc  animated:YES];
    });

}

- (void)didTouchedWeightsChartController:(WeightsChartController *)controller withWeight:(WMWeight *)weight{
    NSLog(@"点击轨迹图表");
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController * vc = [[WeightsHistoryViewController alloc] init];
        [self.navigationController pushViewController:vc  animated:YES];
    });
}

#pragma LCActionSheetDelegate
- (void)actionSheet:(LCActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) {
        [[CameraManager defaultInstance] showCameraWithViewController:self withEdit:YES];
        [CameraManager defaultInstance].delegate = self;
    }else if (1 == buttonIndex) {
        [[CameraManager defaultInstance] showAlbumWithViewController:self withEdit:YES];
        [CameraManager defaultInstance].delegate = self;
    }
}

#pragma CameraManagerDelegate
- (void)pickerDidCancel {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)pickedImage:(UIImage *)image {
    [[WMAppSetting sharedInstance] setCoverImage:image];
    [self dismissViewControllerAnimated:YES completion:NULL];
}
@end
